<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\tool\WxTpl;
use think\facade\Cache;
use think\facade\Event;
use app\common\tool\account\Account;

class Order extends Base
{
    protected $name = 'order';

    protected static $_is_return = [
        '-1' => '退款中',
        '0' => '正常',
        '1' => '部分商品有退款',
        '2' => '全部商品已退款'
    ];

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,photo,mobile,level_id,level_bonus_id,level_video_id,agent_level,syn_level,province,city,district');
    }

    public function behalfUser()
    {
        return $this->hasOne(User::class, 'id', 'behalf_uid')
            ->field('id,code,nickname,photo,mobile');
    }

    public function userField()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,account,photo,nickname');
    }

    public function business()
    {
        return $this->hasOne(Business::class, 'id', 'business_id')
            ->field('id,title,logo,mobile,customer_tel,contacts,full_address');
    }

    public function address()
    {
        return $this->hasOne(Address::class, 'id', 'address_id');
    }

    public function express()
    {
        return $this->hasOne(Express::class, 'id', 'express_id')->field('id,title');
    }

    public function p()
    {
        return $this->hasOne(Area::class, 'code', 'province')->field('code,province as title');
    }

    public function c()
    {
        return $this->hasOne(Area::class, 'code', 'city')->field('code,city as title');
    }

    public function d()
    {
        return $this->hasOne(Area::class, 'code', 'district')->field('code,district as title');
    }


    public function products()
    {
        return $this->hasMany(OrderProduct::class, 'order_id');
    }

    public function productsField()
    {
        return $this->hasMany(OrderProduct::class, 'order_id')
            ->field('id,order_id,pid,title,num,sku_name,vip_price,icon,return_status');
    }

    public function getPayWayAttr($value)
    {
        return get_pay_way($value);
    }

    public function getStatusAttr($value, $data)
    {
        if(isset($data['is_return']) &&$data['is_return'] != 0) $value = -1;
        return getProductOrderStatus($value);
    }

    public function getReturnTextAttr($value, $data)
    {
        return isset(self::$_is_return[$data['is_return']]) ? self::$_is_return[$data['is_return']] :'';
    }

    public static function _all($map, $param, $hasOne, $like = [], $order = 'create_time,desc', $append = [], $filed = '*', $export = false)
    {
        try {
            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;

            $map['is_del'] = 0;
            $product_info = '';
            if(!empty($param['product_info'])){
                $product_info = $param['product_info'];
                unset($param['product_info']);
                unset($map['product_info']);
            }
            $that = parent::where($map);
            if ($hasOne) {
                $that = $that->with($hasOne);
            }

            if($product_info){
                $that->whereLike('product_info', '%' . $product_info . '%');
            }

            if (isset($param['times']) && $param['times']) {
                $times = explode(' - ', $param['times']);
                $that->whereBetweenTime('create_time', $times[0], $times[1]);
            }

            foreach ($like as $v) {
                foreach ($v as $key => $vo) {
                    $that->whereLike($key, '%' . trim($vo) . '%');
                }
            }
            $order = explode(',', $order);
            if ($export) {
                $list = $that->order($order[0], $order[1])->select();
                $count = '';
                if (!empty($append)) {
                    $list->append($append);
                }
            } else {
                $list = $that->page(intval($page), intval($limit))->order($order[0], $order[1])->select();
                $count = getCount($that->fetchSql()->select());
                if (!empty($append)) {
                    $list->append($append);
                }

            }
            foreach ($list as $k=>&$v) {
                $v->pay_time = $v->pay_time ? date('Y-m-d H:i:s', intval($v->pay_time)) : '待付款';
                $v->statusRaw = $v->getData('status');

                /*if($v->pay_state){
                    $products = $v->products()->field('pid,title,num')->select()->toArray();
                    foreach ($products as $item) {
                        $v->product .= $item['title'] . ' * ' .$item['num'] . '；';
                    }
                }else{
                    $products = json_decode($v['data'], true);
                    foreach ($products['product'] as $item){
                        foreach ($item['children'] as $child){
                            $v->product .= $child['title'] . ' * '.$child['num'] . '；';
                        }
                    }
                }
                if($product_title){
                    if(false === strpos($v->product, $product_title)){
                        unset($list[$k]);
                    }
                }*/

                /*$v->product_info = $v->product;
                $v->save();*/

            }

            return ['code' => 0, 'data' => $list, 'count' => $count];

        } catch (\Exception $e) {
            var_dump($e->getMessage());exit;
            return [];
        }
    }


    /**
     * @param $param -- 提交的参数
     * @param $admin -- 后台当前登录管理员
     * @return array
     * 原点 2022年1月8日16:45:49 后台发货订单
     */
    public static function deliver($param, $admin, $business = '')
    {
        parent::startTrans();
        try {
            $info = parent::find($param['id']);
            if ($info->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到相关订单'];
            }

            $product_total = OrderProduct::where('order_id', $info->id)->count();
            $delivered_pids = implode(',', OrderLogistics::where('order_id', $info->id)->column('product_ids'));
            $delivered_count = $delivered_pids ? count(explode(',', $delivered_pids)) : 0;
            $product_count = count($param['product_ids']);

            OrderLogistics::create([
                'order_id' => $info->id,
                'uid'      => $info->uid,
                'product_ids' => implode(',', $param['product_ids']),
                'express_id'  => $param['express_id'],
                'express_code' => $param['express_code'],
                'express_title' => Express::where('id', $param['express_id'])->value('title') ?? '',
                'post_remark' => $param['post_remark'],
                'post_time' => date('Y-m-d H:i:s'),
            ]);

            if($info->status < 3){
                $info->express_id = $param['express_id'];
                $info->express_code = $param['express_code'];
                $info->receiver = $param['receiver'];
                $info->receiver_tel = $param['receiver_tel'];
                $info->province = $param['province'];
                $info->city = $param['city'];
                $info->district = $param['district'];
                $info->address_details = $param['address_details'];
                $info->post_remark = $param['post_remark'];
                $info->post_time = time();

                $info->status = 3;
            }

            if($product_total == $delivered_count + $product_count){
                $info->all_delivered = 1;
            }

            $info->save();

            $msg = '订单发货，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
            $m = '已发货';

            Logs::adds($msg, $admin->id, $admin->admin_name, $admin->business_id);
            parent::commit();

            //发送模板消息
            $tplData = [
                'character_string3' => ['value' => $info->sn, 'color' => '#173177'],//订单号
                'time2' => ['value' => date("Y-m-d H:i:s", $info->post_time), 'color' => '#173177'],//发货时间
                'character_string4' => ['value' => $info->express_code, 'color' => '#173177'],//运单号
            ];
            (new WxTpl())->send($tplData, User::where('id', $info->uid)->value('gzh_openid'), config('pay')['wx_tpl']['order_deliver'], '/order/pages/orderDetail/index?id='.$info->id);

            return ['code' => 1, 'msg' => $m];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function delivered($param, $admin, $business = '')
    {
        parent::startTrans();
        try {
            $info = parent::find($param['id']);
            if ($info->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到相关订单'];
            }

            foreach ($param['logistics'] as $key=>$item){
                $logistic = OrderLogistics::find($item);
                $logistic->express_id = $param['express_id'][$key];
                $logistic->express_code = $param['express_code'][$key];
                $logistic->post_remark = $param['post_remark'][$key];

                $logistic->save();

                if(0 == $key){
                    $info->express_id = $logistic->express_id;
                    $info->express_code = $logistic->express_code;
                    $info->post_remark = $logistic->post_remark;

                    $info->save();
                }
            }

            $msg = '订单发货修改，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
            $m = '已修改发货';

            Logs::adds($msg, $admin->id, $admin->admin_name, $admin->business_id);
            parent::commit();

            return ['code' => 1, 'msg' => $m];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
